from requests import request

from core.logger import logger
from setting import config


class JumpserverClient(object):

    def __init__(self, endpoint=config.JUMPSERVER_HOST, username=config.JUMPSERVER_USERNAME,
                 password=config.JUMPSERVER_PASSWORD):
        self.endpoint = endpoint
        self.username = username
        self.password = password
        self.auth_header = self.login()

    def login(self):
        payload = {"username": self.username, "password": self.password}
        res = request("POST", f'{self.endpoint}/api/users/v1/auth/', data=payload)
        if res.status_code != 200:
            logger.error(f"状态码:{res.status_code} 登录获取token异常....!")
            return {}
        token = res.json().get("token")
        return {"Authorization": f'Bearer {token}'}

    def get_user_assets_by_uuid(self, uuid, timeout=10):
        res = request("GET", f'{self.endpoint}/api/perms/v1/user/{uuid}/assets', headers=self.auth_header,
                      timeout=timeout)
        if res.status_code != 200:
            logger.error(f"状态码:{res.status_code} 用户uuid获取资产异常....!")
            return []
        return res.json()

    def get_users_list(self, timeout=10):
        res = request("GET", f'{self.endpoint}/api/users/v1/users/', headers=self.auth_header, timeout=timeout)
        if res.status_code != 200:
            logger.error(f"状态码:{res.status_code} 获取用户列表信息异常....!")
            return []
        return res.json()


if __name__ == "__main__":
    jumpserver = JumpserverClient()
    print(jumpserver.auth_header)
